package part18;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.SortedMap;

/**
 * @author wcj
 * @Date 2021/6/4 15:37
 * @Version 1.0
 */
public class Part1822 {

    private static final int SIZE = 1024;

    /**
     * 因为新的IO是基于字节的，所以我们需要对其进行数据的转换，将字节转换为字符
     * Java中提供了一个Charset的类，我们可以利用这个类提供的格式对信息在输入的时候进行编码
     * 或者在信息输出的时候进行解码的操作
     *
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        FileChannel out = new FileOutputStream("data2.txt").getChannel();
        out.write(ByteBuffer.wrap("Some text".getBytes()));
        out.close();

        FileChannel in = new FileInputStream("data2.txt").getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(SIZE);
        in.read(buffer);
        buffer.flip();

        System.out.println(buffer.asCharBuffer());
        buffer.rewind();
        String encoding = System.getProperty("file.encoding");
        System.out.println("Decoding using " + encoding + ":" + Charset.forName(encoding).decode(buffer));

        out = new FileOutputStream("data2.txt").getChannel();
        out.write(ByteBuffer.wrap("Some text".getBytes("UTF-16BE")));
        out.close();

        in = new FileInputStream("data2.txt").getChannel();
        in.read(buffer);
        buffer.flip();
        System.out.println(buffer.asCharBuffer());

        test();
    }

    public static void test() {
        SortedMap<String, Charset> charsetSorts = Charset.availableCharsets();
        Iterator<String> iterator = charsetSorts.keySet().iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            System.out.println(next);
        }
    }
}
